﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CacheService.Standard;
using Common.Standard;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace WebApi.Filter
{
    public class NoLoginAttribute : Attribute
    {
    }
    public class LoginFilterAttribute : IActionFilter
    {
        ICache cache;
        public LoginFilterAttribute(ICache _cache)
        {
            this.cache = _cache;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            
            var actiondescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            //控制器上是否有过滤标签
            var no_login_controller = context.Controller.GetType().IsDefined(typeof(NoLoginAttribute), true);
            if (no_login_controller)
            {
                return;
            }
            //控制器上是否有过滤标签
            var no_login_action = actiondescriptor.MethodInfo.IsDefined(typeof(NoLoginAttribute), true);
            if (no_login_action)
            {
                return;
            }
            var key = context.HttpContext.Request.Headers["logincode"].FirstOrDefault();
            if ( string.IsNullOrWhiteSpace(key) || !cache.hasKey($"{key}:user"))
            {
                if (actiondescriptor.MethodInfo.ReturnType.Name == "IActionResult")
                {
                    context.Result = new RedirectResult("/login");
                }
                else
                {
                    throw new Error($"用户尚未登录-{key}");
                }
                return;
            }

            context.HttpContext.Items.Add("token", key);
            
        }
    }
}
